#!/bin/bash
# https://www.oracle.com/java/technologies/downloads/#jdk8-windows
CURRENT_DIR="$(pwd)"
JDK_FILE="jdk-8u421-linux-x64.tar.gz"
INSTALL_DIR="/usr/local"

set -u -e


color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}




if [ -d "${INSTALL_DIR}/jdk" ];then
	color "${INSTALL_DIR}已存在jdk！" 1
	exit
else
	color "检测到${INSTALL_DIR}不存在jdk模块，正在创建..." 2
	[ -d ${INSTALL_DIR} ] || mkdir -p ${INSTALL_DIR}

	tar -xf "$JDK_FILE" -C "$INSTALL_DIR/"
	cd $INSTALL_DIR;ln -s jdk* jdk;cd $CURRENT_DIR
	cat > /etc/profile.d/jdk.sh<<-EOF
	export JAVA_HOME=/usr/local/jdk
	export PATH=\$PATH:\$JAVA_HOME/bin
	EOF
	color "JDK 安装完成，执行source /etc/profile.d/jdk.sh 在当前bash中生效." 0

fi
